<!--  画布模板  -->
<template>
    <div class="page-container">
        <el-form label-position="right" label-width="100px" ref="form" :model="tempForm" class="flex_cell flex_col"
            :rules="rules">
            <el-container v-loading="loading">
                <el-aside class="flex_col  pd_r1 mg_r1" style="width: 460px;border-right: 2px dotted gray">
                    <el-form-item :label="$tt('label_template_name')" prop="tempName">
                        <ex_super_input v-model="tempForm.tempName" class="w_fill">
                        </ex_super_input>
                    </el-form-item>
                    <el-form-item :label="$tt('label_business_type')" prop="refType">
                        <ex_super_input :value="tempForm.refType" class="w_fill" type="select" :attrs="{
            enum: 'PrintBussinessTypeEnum',
        }" @change="refTypeChange" />
                    </el-form-item>
                    <div class="flex_col flex_cell">
                        <ex_header_spiler :title="$tt('label_available_business_param')">
                            <div>
                                <el-dropdown @command="e => this.addFixedElement(e)">
                                    <el-button type="primary">
                                        {{ $t('label_add_fixed_element') }}<i
                                            class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item command="TEXT">
                                            {{ $t('label_text') }}
                                        </el-dropdown-item>
                                        <el-dropdown-item command="BARCODE">
                                            {{ $t('label_barcode') }}
                                        </el-dropdown-item>
                                        <el-dropdown-item command="QRCODE">
                                            {{ $t('label_qrcode') }}
                                        </el-dropdown-item>
                                        <el-dropdown-item command="IMAGE">
                                            {{ $t('label_img') }}
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                                <el-dropdown @command="e => this.addElement(null, e)">
                                    <el-button type="primary">
                                        {{ $t('label_add_shape') }}<i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item command="RECTANGLE">
                                            {{ $t('label_rectangle') }}
                                        </el-dropdown-item>
                                        <!-- <el-dropdown-item command="LINE">
                                            {{ $t('label_line') }}
                                        </el-dropdown-item> -->
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                        </ex_header_spiler>
                        <ex_super_table :data="serviceParams" v-bind="serviceParamsOption" :autoFlex="true">
                        </ex_super_table>
                    </div>
                    <div class="flex_col flex_cell">
                        <ex_header_spiler :title="$tt('label_elements_drawn')">
                            <el-form-item prop="elementDrawList" label-width="0px" class="flex_cell">
                            </el-form-item>
                        </ex_header_spiler>
                        <ex_super_table :data="elementDrawList" v-bind="elementDrawOption" :autoFlex="true"
                            @row-click="rowClick">
                            <template v-slot:extra_attrs="{ row, $index }">
                                <div class="flex_row flex_justify_sa">
                                    <el-button type="danger" @click="e => clickRemove(row)">
                                        {{ $tt('label_remove') }}
                                    </el-button>
                                    <el-button type="primary" @click="e => clickModity(row, $index)">
                                        {{ $tt('label_modify_attribute') }}
                                    </el-button>

                                </div>
                            </template>
                        </ex_super_table>
                    </div>
                </el-aside>
                <el-container class="flex_col">
                    <div>

                        <el-row>
                            <el-col>
                                <el-form-item :label="$tt('label_template_dimension')">
                                    <div class="flex_row">
                                        {{ $tt('label_width') }}
                                        {{ $addUnit(tempForm.canvasWidth, tempForm.switchUnit) }}
                                        *
                                        {{ $tt('label_height') }}
                                        {{ $addUnit(tempForm.canvasHeight, tempForm.switchUnit) }}

                                        <el-button @click="changeSize" type="primary" class="mg_l2">
                                            {{ $tt('label_modify_template_dimension') }}</el-button>

                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col style="width: 400px;">
                                <el-form-item :label="$tt('label_canvas_zoom')">
                                    <el-slider v-model="tempForm.transformScale"
                                        :format-tooltip="e => (1 + (e * 2 / 100)).toFixed(2)"
                                        @input="inputTransformScale"></el-slider>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                    <el-main class="flex_col">
                        <div style="overflow: auto;flex:1 1 0;">
                            <div ref="mainContainer" style="position: relative;transform-origin: 0% 0%">
                                <div :id="mainCanvasDiv" :ref="mainCanvasDiv" @dragover="dragoverCanvas"
                                    class="mainCancasCss" style="transform-origin: 0% 0%">
                                    Not Supported Canvas。
                                </div>
                                <div class="contextmenuFloat" :style="styleTabContextMenu">

                                    <div :class="{ 'item': true, 'select': true, }" v-for="(item, i) in contextmenuList"
                                        :key="i" @click="rowClick(item)">
                                        {{ $t('label_select') }}{{ $formatNameCode(item.name, item.code) }}
                                    </div>
                                    <div class="item remove" @click="contextmenuRemove(contextmenuList)">
                                        {{ $t('label_remove_current_list') }}
                                    </div>
                                </div>
                            </div>


                        </div>
                        <div class="mg_v2 flex_row ">
                            <div class="flex_cell flex_row ">
                                <el-button type="primary" @click="previewClick">
                                    {{ $tt('label_preview') }}
                                </el-button>
                                <el-button type="primary" @click="refTypeSubmit">
                                    {{ $tt('label_save') }}
                                </el-button>
                                <!-- <el-button class="mg_l1" type="danger" v-if="id" @click="deleteTemp">{{
                                    $tt('label_delete_template')
                                }}</el-button> -->
                                <el-button class="mg_l1" @click="copyTemplate">
                                    {{ $tt('label_template_data') }}
                                </el-button>
                                <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
                            </div>

                        </div>
                    </el-main>
                </el-container>
            </el-container>
        </el-form>
        <ex_super_dialog_form ref="formDialog" v-bind="formDialog" @afterSubmitSuccess="formDialogSubmitAfter">
        </ex_super_dialog_form>
        <ex_super_dialog_form ref="previewDialog" v-bind="previewDialog" @afterSubmitSuccess="previewSubmitAfter">
        </ex_super_dialog_form>
        <el-dialog :title="$tt('label_template_preview')" :visible.sync="previewVisible" custom-class="dialog_big">
            <el-image ref="preview" :src="previewData" v-loading="previewLoading" fit="contain"
                :style="`height: ${previewHeight};width: ${previewWidth};object-fit: contain; border: gray dotted 2px;`"
                :preview-src-list="[previewData]">
                <div slot="error" class="color_danger  flex_center flex_col " style="font-size: 16px;height: 100%;"
                    v-if="previewError">
                    <div class="bold mg_1">{{ $tt('tip_photo_load_fail') }}!</div>
                    <div class="mg_1" style="font-size: 15px;word-break: break-all;">
                        {{ previewError }}</div>
                </div>
            </el-image>
            <div class="flex_row_center" v-if="!previewError && previewUrlParams">
              <el-button class="mg_l2" type="primary" @click="printBrowser">
                    {{ $tt('label_browser_print') }} {{ $t('label_test') }}</el-button>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="previewVisible = false">{{ $tt('label_close') }}</el-button>
            </span>
        </el-dialog>
        <ex_super_dialog_form ref="imageDialog" v-bind="imageDialog" @afterSubmitSuccess="imageDialogSubmitAfter" />




    </div>
</template>
<script >

import router_params from '@/mixin/router_params';
import Konva from 'konva'
import JsBarcode from 'jsbarcode'
import qrcode from 'qrcode'
// let stageCanvas = null
// let stageMainLayer = null
export default {
    mixins: [router_params],
    title: 'label_print_template_edit',
    data() {
        return {
            edit: false,
            loading: false,
            mainCanvasDiv: "mainCanvasDiv" + Math.random(),

            contextmenuList: [],
            styleTabContextMenu: {
                top: "100px",
                left: "100px",
                'min-width': '200px',
                display: "none",
            },
            // templateList: [],

            serviceParams: [],
            serviceTableParams: null,
            serviceParamsOption: {
                'highlight-current-row': false,
                model: [
                    {
                        label: 'label_element_name', key: 'name', align: 'left',
                        'min-width': 140,
                        formatter: (r, c, v, i) => this.$formatNameCode(v, r.code)
                    },
                    {
                        label: 'label_operate', 'width': 120, type: 'operate',
                        operate: [
                            {
                                if: (row) => !!this.judgeServiceParamsTable(row),
                                label: 'label_add_table',
                                click: (row) => this.addElement(_.cloneDeep(row), "TABLE")
                            },
                            {
                                if: (row) => !this.judgeServiceParamsTable(row),
                                type: 'more', label: 'label_add_element',
                                items: [
                                    { label: 'label_text', click: (row) => this.addElement(row, "TEXT") },
                                    { label: 'label_barcode', click: (row) => this.addElement(row, "BARCODE") },
                                    { label: 'label_qrcode', click: (row) => this.addElement(row, "QRCODE") },
                                ],
                            }
                        ]
                    },

                ],
            },
            elementDrawList: [],
            elementDrawOption: {
                'highlight-current-row': false,
                'cell-style': this.cellStyle,
                model: [
                    {
                        label: 'label_element_name', key: 'name', align: 'left', 'min-width': 140, 'show-overflow-tooltip': true,
                        render: (h, { row }) => {
                            return (<div class={row.isRequired ? 'label_require_before' : ''}>
                                {this.$formatNameCode(row.name, row.code)}
                            </div>)
                        }
                        // formatter: (r, c, v, i) => this.$formatNameCode(v, r.code)
                    },
                    {
                        type: 'operate', 'width': 120, //slot: 'extra_attrs',
                        operate: [
                            {
                                label: 'label_modify_attribute', click: (row, $index) => {
                                    this.clickModity(row, $index)
                                }
                            },
                            {
                                label: 'label_delete', type: "confirm-button", message: 'label_fms_bank_card_confirm_delete',
                                buttonClass: "button_text_danger", confirmButtonType: 'danger',
                                done: (row, $index) => {
                                    this.clickRemove(row)
                                }
                            },

                        ]

                    },
                    // {
                    //     type: 'operate', width: 120, operate: [
                    //         { label: 'label_remove', click: this.clickRemove },
                    //     ]
                    // }
                ],
            },
            syncAttrsList: ['fontSize', 'autoWrap'],
            syncAttrsUnitList: ['x', 'y', 'width', 'height', 'strokeWidth'],


            tempForm: {
                id: null,
                refType: null,

                tempName: "",
                canvas_temp_size: "",

                canvasWidth: 100,
                canvasHeight: 100,

                backgroundGrid_temp: 5,
                backgroundGrid: 5,

                switchUnit_temp: 'mm',
                switchUnit: 'mm',

                transformScale: 0,
            },
            rules: {
                'tempName': { required: true, message: this.$tt('tip_can_no_empty'), label: "label_template_name", },
                'refType': { required: true, message: this.$tt('tip_can_no_empty'), label: "label_business_type", },
                'elementDrawList': {
                    required: true, label: "label_elements_drawn", validator: (r, v, cb) => {
                        this.elementDrawList.length == 0 ? cb(this.$tt('tip_can_no_empty')) : cb()
                    },
                },
            },


            unitList: [{ label: 'mm', value: 'mm' }, { label: 'cm', value: 'cm' }, { label: 'px', value: 'px' }],
            formDialog: {
                customClass: 'dialog_auto',
                form: {
                    inputClass: "bold form_input_small",
                    model: [
                        { header: "label_base_info", },
                        {

                            grid: [
                                [
                                    { span: 12, col: { key: 'name', label: 'label_element_name', formType: "text" }, },
                                    { span: 12, col: { key: 'code', label: 'label_element_code', formType: "text" }, },
                                ],
                                [
                                    { span: 12, col: { key: 'type', label: 'label_draw_type', formType: "text" }, },
                                    { span: 12, col: { key: 'isRequired', label: 'label_is_required', type: "el-checkbox", }, },
                                ],
                                [
                                    { span: 12, col: { key: 'x', label: 'label_coord_x', append: "mm", }, },
                                    { span: 12, col: { key: 'y', label: 'label_coord_y', append: "mm", }, },
                                ],
                                [
                                    { span: 12, col: { key: 'width', label: 'label_element_width', append: "mm", if: (data) => data.type != 'TEXT' || data.autoWrap, }, },
                                    { span: 12, col: { key: 'height', label: 'label_element_height', append: "mm", if: (data) => data.type != 'TEXT', }, },
                                ],
                            ],


                        },
                        {
                            if: (data) => !this.judgeServiceParamsTable(data),
                            grid: [
                                [
                                    { span: 12, col: { key: 'isAutoScale', label: 'label_auto_scale', type: "el-checkbox", if: (data) => !['TEXT', 'RECTANGLE'].includes(data.type) }, },
                                ],
                                [
                                    { span: 12, col: { if: (data) => data.type == 'TEXT', key: 'fontSize', label: 'label_word_size', type: "el-input-number", attrs: { min: 1, max: 50, }, }, },
                                    { span: 12, col: { if: (data) => data.type == 'TEXT', key: 'autoWrap', label: 'label_text_auto_wrap', type: "el-checkbox", }, },
                                ],
                                [
                                    { span: 12, col: { if: (data) => data.type == 'RECTANGLE', key: 'strokeWidth', label: 'label_stroke_width', append: "mm", }, },
                                ],
                            ]
                        },
                        {
                            if: (data) => this.judgeServiceParamsTable(data),
                            grid: [
                                [
                                    {
                                        key: 'isExpandPage', label: 'label_is_expand_page', //type: "el-checkbox",
                                        render: (h, { data, item }) => {
                                            const value = data.tableConfig[item.key]
                                            return (
                                                <el-checkbox value={value} onInput={e => this.$set(data.tableConfig, item.key, e)} />
                                            )
                                        }
                                    },
                                    { key: 'fontSize', label: 'label_word_size', type: "el-input-number", attrs: { min: 1, max: 50, }, },

                                ],
                                [
                                    {
                                        span: 24, col: {
                                            key: 'columns', label: 'label_list_config',
                                            render: (h, { data, item }) => {
                                                const model = [
                                                    {
                                                        key: "check", label: "label_used", width: 100,
                                                        render: (h, { row, column }) => {
                                                            const value = row[column.property]
                                                            return (
                                                                <el-checkbox value={value} onInput={e => this.$set(row, column.property, e)} />
                                                            )
                                                        }
                                                    },
                                                    {
                                                        key: "index", label: "label_sort_index", "min-width": 150,
                                                        render: (h, { row, column }) => {
                                                            const value = row[column.property]
                                                            return (
                                                                <el-input-number class="w_fill" value={value} min={0} max={100} onInput={e => this.$set(row, column.property, e)} />
                                                            )
                                                        }
                                                    },
                                                    { key: "name", label: "label_name", width: 150, },
                                                    {
                                                        key: "widthPercent", label: "label_width_percent", "min-width": 150,
                                                        render: (h, { row, column }) => {
                                                            const value = row[column.property]
                                                            return (
                                                                <el-input-number class="w_fill" value={value} min={0} max={100} onInput={e => this.$set(row, column.property, e)} />
                                                            )
                                                        }
                                                    },
                                                ]
                                                return (
                                                    <ex_super_table data={data.tableColumns} showIndex={false} model={model} />
                                                )
                                            }
                                        },
                                    },
                                ],
                            ]
                        },
                    ],
                    rules: {
                        'isRequired': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
                        'isAutoScale': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
                        'x': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
                        'y': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
                        'fontSize': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
                        'autoWrap': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
                        'width': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
                        'height': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
                        'strokeWidth': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],

                    },
                }
            },
            previewDialog: {
                'custom-class': 'dialog_default',
                form: {
                    itemClass: "form_item_mini", inputClass: "form_input_small",
                    // formClass: "form_mini_col2 ",
                    // inline: true,
                    model: [],
                    rules: {},
                }

            },
            previewLoading: false,
            previewVisible: false,
            previewWidth: '100px',
            previewHeight: '100px',

            previewData: null,
            previewError: null,
            previewUrlParams: {},

            clientIdAndPrintName: null,
            clientId: "",
            printerName: "",

            stageCanvas: null,
            stageMainLayer: null,

            imageDialog: {
                customClass: 'dialog_auto',
                form: {
                    itemClass: "form_item_default",
                    model: [
                        {
                            key: 'value', label: 'label_img',
                            rules: (r, c, v) => {
                                return [
                                    { required: true, type: "array", message: this.$tt('tip_can_no_empty'), trigger: 'change' },
                                    {
                                        trigger: 'change', validator: (rule, value, cb) => {
                                            if (r.isUpload) {
                                                cb(this.$tt("label_uploading"))
                                            } else {
                                                cb()
                                            }
                                        },
                                    }
                                ]
                            },
                            render: (h, { data, item }) => {
                                const value = data[item.key]
                                return (<ex_super_upload value={value} type="image"
                                    onInput={e => this.$set(data, item.key, e)}
                                    onIsUploadChange={e => this.$set(data, 'isUpload', e)}
                                    limit={1}
                                />)
                            },
                        },
                    ],
                }
            },
        }
    },
    destroyed() {
        this.stageCanvas.clearCache();
        this.stageCanvas.clear();
        this.stageCanvas = null
    },


    mounted() {
        this.stageCanvas = new Konva.Stage({
            container: this.mainCanvasDiv,
        });
        // this.resize()
        this.stageMainLayer = new Konva.Layer();

        this.stageCanvas.add(this.stageMainLayer);

        // this.stageMainLayer.focus();
        this.stageMainLayer.draw();
        // this.stageCanvas.on('click  tap', (e) => {
        //     console.log('click', e)
        // });
        this.stageCanvas.on('click', (e) => {
            this.styleTabContextMenu.display = "none";
            if (!e.evt || e.evt.button == 0) {
                this.clickElement(e)
            }
        });
        this.stageCanvas.on('contextmenu', (e, t) => {

            let mousePos = this.stageCanvas.getPointerPosition();
            let intersectGroup = this.elementDrawList.filter(element => element.instance && element.instance.intersects(mousePos))
            if (_.isEmpty(intersectGroup)) {
                this.styleTabContextMenu.display = "none";
            } else {
                this.styleTabContextMenu.display = "";
                this.styleTabContextMenu.top = mousePos.y + 10 + "px";
                this.styleTabContextMenu.left = mousePos.x + 10 + "px";
                this.contextmenuList = intersectGroup.sort((a, b) => b.instance.zIndex() - a.instance.zIndex())
                e.evt.preventDefault();
                // console.log('contextmenu', intersectGroup)

            }
            // var group = this.stageCanvas.getIntersection(mousePos, 'Group');


        });

        var container = this.stageCanvas.container();


        container.tabIndex = 1;
        container.focus();
        container.addEventListener('keydown', (e) => {
            const item = _.find(this.elementDrawList, it => it.select)
            if (item && item.instance) {
                if (e.keyCode === 37) {
                    item.instance.x(item.instance.x() - 1);
                } else if (e.keyCode === 38) {
                    item.instance.y(item.instance.y() - 1);
                } else if (e.keyCode === 39) {
                    item.instance.x(item.instance.x() + 1);
                } else if (e.keyCode === 40) {
                    item.instance.y(item.instance.y() + 1);
                } else if (e.keyCode === 46) {
                    this.clickRemove(item)
                    e.preventDefault();
                    return
                }
                this.syncAttrs(item.instance, item)
            }
            e.preventDefault();
        });
        return


    },


    //Vue实例方法列表
    methods: {

        //判断可绘制元素是否为table类型
        judgeServiceParamsTable(row) {
            return (row.tableConfig)
        },
        contextmenuRemove(list) {
            _.clone(list).forEach(it => {
                this.clickRemove(it)
                const i = _.indexOf(this.contextmenuList, it)
                if (i >= 0) {
                    this.contextmenuList.splice(i, 1)
                }
            })
            this.styleTabContextMenu.display = "none";
        },
        getStageCanvas() {
            return this.stageCanvas
        },
        getMainLayer() {
            return this.stageMainLayer
        },
        clientHander(list) {
            const out = _.concat([], ...list.map(it => it.printerConfigList.map(pr => {
                return {
                    _value: it.clientId + ' - ' + pr.printerName,
                    _label: it.customerClientName + ' - ' + pr.printerName + ` - (${pr.paperSize})`,
                    clientId: it.clientId,
                    printerName: pr.printerName,
                }
            })))
            return out
        },
        changeClientPrint(e) {
            this.clientIdAndPrintName = e._value
            this.clientId = e.clientId
            this.printerName = e.printerName
        },
        clickModity(row, index) {
            const { instance, ...other } = row

            const item = _.cloneDeep(other)
            item._index = index
            if (item.tableConfig) {
                const tableRefType = item.tableConfig.tableRefType
                const columns = item.tableConfig.columns
                item.tableColumns = this.serviceTableParams[tableRefType] ? this.serviceTableParams[tableRefType].tableColumnItems : []
                item.tableColumns.forEach(it => {
                    it.check = columns.some(c => c.code == it.code)
                    const citem = _.find(columns, c => c.code == it.code)
                    if (citem) {
                        it.index = citem.index
                        it.widthPercent = citem.widthPercent
                    }
                })
                item.tableColumns = _.sortBy(item.tableColumns, c => Number(c.index))
            }

            this.$refs.formDialog.showNew({
                title: this.$tt("label_modify_attribute"),
                data: item,
                onlySetData: true,
            })
        },
        formDialogSubmitAfter(data) {
            const { _index, ...item } = data
            const row = this.elementDrawList[_index]
            if (row && row.instance) {
                if (item.type == 'TEXT') {
                    if (item.autoWrap == false) {
                        item.width = this.$dpi.convert(this.getStageCanvas().width() - row.instance.x(), 'px', this.tempForm.switchUnit)
                    }
                } else if (item.type == "TABLE") {
                    item.tableConfig.columns = _.sortBy(item.tableColumns.filter(it => !!it.check), c => Number(c.index))
                    delete item.tableColumns
                }
                const setAttrs = {}
                _.forOwn(item, (v, k) => {
                    this.$set(row, k, v)
                    if (this.syncAttrsList.includes(k)) {
                        if (row.instance[k]) {
                            setAttrs[k] = v
                        }
                    } else if (this.syncAttrsUnitList.includes(k)) {
                        if (row.instance[k]) {
                            const value = this.$dpi.convert(v, this.tempForm.switchUnit, 'px')
                            setAttrs[k] = Number(value)
                        }
                    }
                })
                const newAttrs = Object.assign({}, row.instance.getAttrs(), setAttrs)


                row.instance.setAttrs(newAttrs);
                if (item.type == 'TEXT') {
                    row.instance.height(null)
                }

                this.setFontWrapTransformer(row)
                this.syncAttrs(row.instance, row)
            }
        },
        init_data_default(into_params) {

            this.edit = !!into_params.edit
            if (this.edit && into_params.id) {
                this.loading = true
                this.$ajax({
                    url: "/print-api/template/PrintTemplateCfgRpc/detail.json",
                    method: 'post',
                    data: { id: into_params.id },
                    success: (res) => {
                        if (!res.data) return this.$message.error(this.$tt("label_data_loss"))
                        this.fixTabLabel(res.data.templateName)
                        const tableCfgList = res.data.tableCfgList || {}

                        this.refTypeChangeNet(res.data.refType, (data) => {
                            this.loadTemp(res.data)
                        })
                    },
                    complete: () => {
                        this.loading = false
                    }
                })
            } else {
                this.loadTemp(null)
            }
            this.fixTabLabel()
        },
        fixTabLabel(name) {
            if (this.edit && name) {
                this.$emit("tagModifyLabel", { _key: 'label_name_code', i18n: { name: true }, name: { _key: "label_edit_any", i18n: true, type: "label_print_template" }, code: name })
            } else {
                this.$emit("tagModifyLabel", { _key: "label_new_any", i18n: true, type: "label_print_template" })
            }
        },
        unitChange(e) {


            this.tempForm.switchUnit_temp = e
        },
        clickRemove(row,) {
            const i = _.indexOf(this.elementDrawList, row)
            if (row.instance && i >= 0) {
                this.removeTransform(row.instance)
                row.instance.destroy();
                this.elementDrawList.splice(i, 1)
            }
        },
        syncAttrs(e, item) {
            this.styleTabContextMenu.display = "none";
            if (!item) {
                item = _.find(this.elementDrawList, it => it.instance == e)
            }

            if (item) {
                if (item.type == 'TEXT' && item.autoWrap == false) {
                    const newWidth = this.getStageCanvas().width() - e.x()
                    if (newWidth > 0) {
                        e.width(newWidth)
                    }
                }
                this.syncAttrsList.forEach(key => {
                    if (e[key]) {
                        this.$set(item, key, e[key]())
                    }
                })
                this.syncAttrsUnitList.forEach(key => {
                    if (e[key]) {
                        const value = this.$dpi.convert(e[key](), 'px', this.tempForm.switchUnit)
                        this.$set(item, key, value)
                    }
                })

            }
        },
        changeAttrs(row, key, e) {
            if (row.instance) {
                const data = {}
                if (this.syncAttrsList.includes(key)) {
                    if (row.instance[key]) {
                        data[key] = e
                    }
                }
                if (this.syncAttrsUnitList.includes(key)) {
                    if (row.instance[key]) {
                        const value = this.$dpi.convert(e, this.tempForm.switchUnit, 'px')
                        data[key] = Number(value)
                    }
                }
                if (key == 'autoWrap') {
                    this.setFontWrapTransformer(row)
                }
                if (!_.isEmpty(data)) {

                    const oldAttrs = Object.assign({}, row.instance.getAttrs(), data)
                    if (oldAttrs.points) {
                        oldAttrs.points = [
                            // oldAttrs.x, oldAttrs.y, oldAttrs.x + oldAttrs.width, oldAttrs.y + oldAttrs.height,
                            0, 0, oldAttrs.width, oldAttrs.height,
                        ]
                    }
                    row.instance.setAttrs(oldAttrs);
                }

            }
        },
        clickElement(e) {
            this.clearTransform()
            if (e.target === this.getStageCanvas()) {
                this.getMainLayer().draw();
                return;
            }
            const item = _.find(this.elementDrawList, it => it.instance == e.target)
            if (item) {
                this.addTransformer(e.target, item)
            }
        },
        removeTransform(e) {
            const _transList = this.getStageCanvas().find('Transformer')
            _transList.forEach(it => {
                if (it._nodes) {
                    for (let i = 0; i < it._nodes.length; i++) {
                        const tagert = it._nodes[i]
                        if (tagert == e) {
                            return it.destroy()
                        }
                    }
                }
            })
        },
        clearTransform() {
            const _transList = this.getStageCanvas().find('Transformer')
            _transList.forEach(it => {
                if (it._nodes) {
                    it._nodes.forEach(e => {
                        const item = _.find(this.elementDrawList, it => it.instance == e)
                        if (item) {
                            item.select = false
                            this.syncAttrs(e, item)
                        }
                    })
                }
                it.destroy()
            })
        },


        addTransformer(e, item) {

            if (!item) return
            const config_Transformer = {
                rotateEnabled: false,
                boundBoxFunc: (oldBox, newBox) => {
                    if (newBox.x < 0 || newBox.y < 0 ||
                        (newBox.x + newBox.width) > this.getStageCanvas().width() || (newBox.y + newBox.height) > this.getStageCanvas().height()) {
                        return oldBox
                    } else {
                        return newBox
                    }
                }
            }
            item.select = true
            this.syncAttrs(e, item)

            if (item.autoWrap == false && item.type == 'TEXT') {
                config_Transformer.enabledAnchors = []
            }
            const tr = new Konva.Transformer(config_Transformer);
            this.getMainLayer().add(tr);

            tr.attachTo(e);
            e.moveToTop()
            this.getMainLayer().draw();
            this.setFontWrapTransformer(item, tr)
        },
        setFontWrapTransformer(item, _transformer) {
            if (item.type != 'TEXT') return

            if (!_transformer) {
                _transformer = _.find(this.getStageCanvas().find('Transformer'), it => it._nodes && it._nodes.some(t => t == item.instance))
            }
            if (_transformer) {
                if (item.autoWrap == false) {
                    _transformer.enabledAnchors([])
                } else {
                    _transformer.enabledAnchors(['middle-right', 'middle-left',])
                }
            }
        },
        rowClick(row) {
            if (row.select) return

            this.clearTransform()
            this.addTransformer(row.instance, row)
        },
        cellStyle({ row, column, rowIndex, columnIndex }) {
            if (row.select) {
                return {
                    'background-color': 'rgb(208, 228, 249)'
                }
            }
            // return 'tableCell_noHoverLight'
        },
        //添加画布上实际绘制元素
        addElementInstance(elementDraw, instance) {


            instance.on('transform', (e) => {


                instance.setAttrs({
                    x: instance.x(),
                    y: instance.y(),
                    points: [
                        0,
                        0,
                        (instance.width() * instance.scaleX()),
                        (instance.height() * instance.scaleY()),
                    ],
                    width: instance.width() * instance.scaleX(),
                    height: instance.height() * instance.scaleY(),
                    scaleX: 1,
                    scaleY: 1,
                });
                this.syncAttrs(instance, elementDraw)
            });
            instance.draggable(true)
            instance.dragBoundFunc((pos) => {
                const authWidth = elementDraw.type == 'TEXT' && elementDraw.autoWrap == false
                let newY = pos.y;
                if (pos.y < 0) {
                    newY = 0
                } else if (!authWidth && (pos.y + instance.height() - 1) > this.getStageCanvas().height()) {
                    newY = this.getStageCanvas().height() - instance.height()
                }
                let newX = pos.x;
                if (pos.x < 0) {
                    newX = 0
                } else if (!authWidth && (pos.x + instance.width() - 1) > this.getStageCanvas().width()) {
                    newX = this.getStageCanvas().width() - instance.width()
                }
                return {
                    x: newX,
                    y: newY
                };
            })
            instance.on('dragmove', (e) => {
                this.syncAttrs(instance, elementDraw)
            });
            this.getMainLayer().add(instance);
            this.getMainLayer().batchDraw()
            elementDraw.instance = instance
            this.elementDrawList.push(elementDraw)

            this.syncAttrs(instance, elementDraw)
        },
        imageDialogSubmitAfter(data) {
            if (data && !_.isEmpty(data.value)) {
                this.addElement(null, data.type, {
                    name: "图片",
                    value: data.value[0].filePath,
                })
            }
        },
        addFixedElement(e) {
            if (e == "IMAGE") {
                this['$refs']['imageDialog'].showNew({
                    title: this.$t("tip_place_upload_fixed_image"),
                    data: {
                        type: e,
                    },
                    onlySetData: true,
                })
            } else {
                this.$prompt(this.$t('tip_place_input_fixed_value'), this.$t('label_tip'), {
                    inputValidator: (v) => {
                        if (!v || !v.trim()) return this.$t("tip_can_no_empty")
                    }
                }).then(({ value }) => {
                    this.addElement(null, e, {
                        name: value,
                        value,
                    })
                }).catch(() => {

                });
            }

        },
        //添加绘制元素，创建画布绘制元素
        addElement(item, e, obj) {

            if (!item) {
                item = {
                    name: '',
                    code: e,
                    width: this.$dpi.convert(this.getStageCanvas().width() / 4, 'px', this.tempForm.switchUnit),
                    height: this.$dpi.convert(this.getStageCanvas().height() / 4, 'px', this.tempForm.switchUnit),
                }
            }
            let instance = null
            let elementDraw = {
                ...item,
                type: e,
                x: 0,
                y: 0,
                instance: instance,
                select: false,
                isRequired: false,
                isAutoScale: true,
            }
            if (elementDraw.type == 'TEXT') {
                elementDraw.fontSize = 20
                elementDraw.autoWrap = false
                delete elementDraw.height
            } else if (elementDraw.type == 'LINE' || elementDraw.type == 'RECTANGLE') {
                elementDraw.strokeWidth = this.$dpi.convert(10, 'px', this.tempForm.switchUnit)
            } else if (['RECTANGLE', 'IMAGE', 'QRCODE', 'TABLE'].includes(elementDraw.type)) {
                elementDraw.width = this.$dpi.convert(this.getStageCanvas().width() / 4, 'px', this.tempForm.switchUnit)
                elementDraw.height = this.$dpi.convert(this.getStageCanvas().height() / 4, 'px', this.tempForm.switchUnit)
            } else if (['BARCODE'].includes(elementDraw.type)) {
                elementDraw.width = this.$dpi.convert(this.getStageCanvas().width() / 2, 'px', this.tempForm.switchUnit)
                elementDraw.height = this.$dpi.convert(this.getStageCanvas().height() / 4, 'px', this.tempForm.switchUnit)
            }
            // console.log(JSON.stringify(elementDraw),JSON.stringify(obj))

            Object.assign(elementDraw, obj)
            // console.log(JSON.stringify(elementDraw),JSON.stringify(obj))

            if (elementDraw.type == 'LINE') {

                instance = new Konva.Line({
                    points: [
                        this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px'),
                        this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px'),
                        this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px') + this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px'),
                        this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px') + this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px'),
                    ],
                    x: this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px'),
                    y: this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px'),
                    width: this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px'),
                    height: this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px'),
                    stroke: 'black',
                    strokeWidth: this.$dpi.convert(elementDraw.strokeWidth, this.tempForm.switchUnit, 'px'),
                })
                this.addElementInstance(elementDraw, instance)
            } else if (elementDraw.type == 'RECTANGLE') {

                instance = new Konva.Rect({
                    x: this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px'),
                    y: this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px'),
                    width: this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px'),
                    height: this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px'),
                    fill: 'green',
                    fillEnabled: false,
                    stroke: 'black',
                    strokeWidth: this.$dpi.convert(elementDraw.strokeWidth, this.tempForm.switchUnit, 'px'),
                })
                this.addElementInstance(elementDraw, instance)
            } else if (elementDraw.type == 'IMAGE') {

                let im = new Image()
                im.src = this.$ex_default_download_url + elementDraw.value
                instance = new Konva.Image({
                    image: im,
                    x: this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px'),
                    y: this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px'),
                    width: this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px'),
                    height: this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px'),
                });
                this.addElementInstance(elementDraw, instance)
            } else if (elementDraw.type == 'BARCODE') {


                let im = new Image()//document.createElement('img')
                // im.style.width = `${elementDraw.width}${this.tempForm.switchUnit}`
                // im.style.height = `${elementDraw.height}${this.tempForm.switchUnit}`
                JsBarcode(im, elementDraw.value || elementDraw.code, {
                    format: "CODE128",
                    background: "#00000000",
                    lineColor: elementDraw.value ? "#000000" : "#1a56e8",
                    fontSize: 0,
                    margin: 2,
                });
                instance = new Konva.Image({
                    image: im,
                    x: this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px'),
                    y: this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px'),
                    width: this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px'),
                    height: this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px'),
                });
                this.addElementInstance(elementDraw, instance)
            } else if (elementDraw.type == 'QRCODE') {

                let im = new Image()
                qrcode.toDataURL(elementDraw.value || elementDraw.code, {
                    margin: 2,
                    color: {
                        dark: elementDraw.value ? "#000000" : "#1a56e8",
                        light: "#00000000"
                    },
                    // width: this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px'),
                    // height: this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px'),
                })
                    .then(url => {
                        im.src = url
                        instance = new Konva.Image({
                            image: im,
                            x: this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px'),
                            y: this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px'),

                            width: this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px'),
                            height: this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px'),

                        });
                        this.addElementInstance(elementDraw, instance)
                    })
                    .catch(err => {
                    })
            } else if (elementDraw.type == 'TEXT') {
                const config = {
                    text: elementDraw.value || elementDraw.code,
                    fill: elementDraw.value ? "#000000" : "#1a56e8",
                    wrap: elementDraw.autoWrap ? "warp" : 'none',
                    fontSize: elementDraw.fontSize,
                    x: this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px'),
                    y: this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px'),
                }
                if (elementDraw.width) {
                    config.width = this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px')
                }
                if (elementDraw.height) {
                    config.height = this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px')
                }
                let instance = new Konva.Text(config);


                this.addElementInstance(elementDraw, instance)
            } else if (elementDraw.type == 'TABLE') {


                const tableRefType = elementDraw.tableConfig.tableRefType
                if (tableRefType) {
                    if (!_.has(elementDraw.tableConfig, "isExpandPage")) {
                        elementDraw.tableConfig.isExpandPage = false
                    }
                    const linkTableConfig = this.serviceTableParams[tableRefType]
                    if (linkTableConfig) {
                        if (!_.has(elementDraw.tableConfig, "columns")) {
                            elementDraw.tableConfig.columns = linkTableConfig.tableColumnItems
                        }
                    }
                }


                const config = {
                    text: elementDraw.value || elementDraw.code,
                    fill: elementDraw.value ? "#000000" : "#1a56e8",
                    wrap: elementDraw.autoWrap ? "warp" : 'none',
                    fontSize: elementDraw.fontSize,
                    x: this.$dpi.convert(elementDraw.x, this.tempForm.switchUnit, 'px'),
                    y: this.$dpi.convert(elementDraw.y, this.tempForm.switchUnit, 'px'),
                }
                if (elementDraw.width) {
                    config.width = this.$dpi.convert(elementDraw.width, this.tempForm.switchUnit, 'px')
                }
                if (elementDraw.height) {
                    config.height = this.$dpi.convert(elementDraw.height, this.tempForm.switchUnit, 'px')
                }
                let instance = new Konva.Text(config);
                this.addElementInstance(elementDraw, instance)
            }
        },
        changeSize() {
            this.$prompt('请输入模板 宽度*高度，单位' + this.tempForm.switchUnit, this.$tt("label_tip"), {
                inputValidator: (value) => {
                    const list = value ? value.split('*').map(it => it ? it.trim() : "").filter(it => it) : []
                    if (list.length == 2) {
                        if (list.every(it => this.$reg.DigitNumber(it, 2, 6))) {
                            return true
                        } else {
                            return this.$tt('tip_only_digit_int_length', { digit: 2, int: 6 })
                        }
                    }
                    return "请输入宽度 * 高度"
                },
            }).then(({ value }) => {
                const list = value ? value.split('*').map(it => it ? it.trim() : "").filter(it => it) : []

                this.resize(...list)

            }).catch(() => {

            });
        },

        resize(newWidth, newHeight) {
            // if (!this.canvas_temp_size) {
            //     return this.$message.error(this.$tt("模板尺寸只能为 宽 * 高 "))
            // }
            // const dimens = _.trim(this.canvas_temp_size).split('*')
            // if (dimens.length != 2) {

            // }
            if (newWidth) {
                this.tempForm.canvasWidth = newWidth
            }
            if (newHeight) {
                this.tempForm.canvasHeight = newHeight
            }

            this.tempForm.backgroundGrid = this.tempForm.backgroundGrid_temp
            this.tempForm.switchUnit = this.tempForm.switchUnit_temp

            const widthUnit = this.$dpi.convert(this.tempForm.canvasWidth, this.tempForm.switchUnit, 'px')
            const heightUnit = this.$dpi.convert(this.tempForm.canvasHeight, this.tempForm.switchUnit, 'px')
            const backgroundGridUnit = this.$dpi.convert(this.tempForm.backgroundGrid, this.tempForm.switchUnit, 'px')
            this.getStageCanvas().size({
                width: widthUnit,
                height: heightUnit,
            });
            this.$refs[this.mainCanvasDiv].style.width = `${widthUnit}px`
            this.$refs[this.mainCanvasDiv].style.height = `${heightUnit}px`
            this.$refs[this.mainCanvasDiv].style['background-size'] = `${backgroundGridUnit}px ${backgroundGridUnit}px`

            this.$refs.mainContainer.style.width = `${widthUnit}px`
            this.$refs.mainContainer.style.height = `${heightUnit}px`

            this.elementDrawList.forEach(it => this.syncAttrs(it.instance, it))
        },
        inputTransformScale(e) {
            const scale = (1 + (e * 2 / 100)).toFixed(2)
            // this.$refs[this.mainCanvasDiv].style.transform = `scale(${scale})`
            this.$refs.mainContainer.style.transform = `scale(${scale})`
        },
        dragstartRectangle(e) {
            let ev = e || window.event;
            let element = ev.srcElement || ev.target
            let width = element.clientWidth
            let height = element.clientHeight
            let drawObj = {
                type: 'Rectangle',
                width,
                height,
                lineWidth: 5,
            }
            ev.dataTransfer.setData('draw', JSON.stringify(drawObj));
        },
        dropCanvas(e) {
            let ev = e || window.event;
            let data = ev.dataTransfer.getData('draw');
            let drawObj = JSON.parse(data)
            this.ctx.lineWidth = drawObj.lineWidth;
            this.ctx.strokeRect(ev.offsetX, ev.offsetY, drawObj.width, drawObj.height);   // 绘制矩形边框
            // data(this.ctx,ev.offsetX,ev.offsetY)
            // e.target.appendChild(document.querySelector("#" + data));
        },
        dragoverCanvas(e) {
            let ev = e || window.event;
            ev.preventDefault();
        },
        loadTemp(item) {

            if (item == null) {
                this.tempForm.tempName = ""
                this.tempForm.canvasWidth = 200
                this.tempForm.canvasHeight = 200
                this.tempForm.backgroundGrid_temp = 4
                this.tempForm.backgroundGrid = 4

                this.tempForm.switchUnit_temp = 'mm'
                this.tempForm.switchUnit = 'mm'

                this.tempForm.transformScale = 0

                this.tempForm.id = null
                this.refreshDraw()



            } else {
                this.tempForm.tempName = item.templateName



                this.tempForm.canvasWidth = item.pageWidth
                this.tempForm.canvasHeight = item.pageHeight
                this.tempForm.backgroundGrid_temp = 4
                this.tempForm.backgroundGrid = 4

                this.tempForm.switchUnit_temp = 'mm'
                this.tempForm.switchUnit = 'mm'

                this.tempForm.transformScale = 0

                this.tempForm.refType = item.refType

                this.tempForm.id = item.id
                const list = item.paneItems.map(it => {
                    return {
                        name: it.itemName,
                        code: it.itemCode,
                        value: it.itemValue,
                        type: it.itemType,
                        autoWrap: it.autoWrap,
                        x: it.x,
                        y: it.y,
                        fontSize: it.fontSize,
                        fontType: it.fontType,
                        width: it.pictureWidth,
                        height: it.pictureHeight,
                        strokeWidth: it.lineWidth,
                        isRequired: !!it.isRequired,
                        isAutoScale: !!it.isAutoScale,
                        tableConfig: it.tableConfig,
                    }
                })

                this.refreshDraw(list)

            }


        },
        //输出模板数据
        outTemplate() {
            const list = this.elementDrawList.map(it => {
                return {
                    "itemType": it.type,
                    "itemCode": it.code,
                    "itemName": it.name,
                    "itemValue": it.value,
                    "autoWrap": it.autoWrap,
                    "x": this.$dpi.convert(it.x, this.tempForm.switchUnit, 'mm'),
                    "y": this.$dpi.convert(it.y, this.tempForm.switchUnit, 'mm'),
                    "itemWidth": this.$dpi.convert(it.width, this.tempForm.switchUnit, 'mm'),
                    "fontSize": it.fontSize,
                    "fontType": "宋体",
                    "pictureWidth": this.$dpi.convert(it.width, this.tempForm.switchUnit, 'mm'),
                    "pictureHeight": this.$dpi.convert(it.height, this.tempForm.switchUnit, 'mm'),
                    "endpointX": this.$dpi.convert(it.x + it.width, this.tempForm.switchUnit, 'mm'),
                    "endpointY": this.$dpi.convert(it.y + it.height, this.tempForm.switchUnit, 'mm'),
                    "lineWidth": this.$dpi.convert(it.strokeWidth, this.tempForm.switchUnit, 'mm'),
                    "isRequired": it.isRequired,

                    "isAutoScale": it.isAutoScale,
                    "tableConfig": it.tableConfig,
                }
            })

            return {
                id: this.tempForm.id,
                templateName: this.tempForm.tempName,
                refType: this.tempForm.refType,
                pageWidth: this.$dpi.convert(this.tempForm.canvasWidth, this.tempForm.switchUnit, 'mm'),
                pageHeight: this.$dpi.convert(this.tempForm.canvasHeight, this.tempForm.switchUnit, 'mm'),
                defaultFont: "宋体",
                paneItems: list
            }
        },
        refreshDraw(list) {
            this.resize()
            this.getMainLayer().removeChildren()
            this.elementDrawList = []
            if (list) {
                list.forEach(it => {
                    this.addElement({}, null, it)
                })
            }
        },
        refTypeChange(e,) {
            if (!_.isEmpty(this.elementDrawList) && this.tempForm.refType) {

                this.$confirm(this.$tt('tip_modify_business_type_clear_element'), this.$tt('label_tip'), {
                    type: 'warning'
                }).then(() => {
                    // this.refreshDraw()
                    // this.loadTemp()
                    this.refTypeChangeNet(e)
                    this.refreshDraw()
                }).catch(() => {

                });
                return
            }


            this.refTypeChangeNet(e)
        },

        refTypeChangeNet(e, call) {
            this.loading = true
            this.$ajax({
                url: this.$url['print/template/list'],
                method: 'post',
                data: {
                    refType: e
                },
                success: (res) => {
                    if (res.data) {
                        this.tempForm.refType = e
                        this.serviceTableParams = res.data.tableCfgList

                        this.serviceParams = res.data.usableItems.map(it => {
                            const item = {
                                name: it.itemName,
                                code: it.itemCode,
                            }
                            if (it.tableRefType) {
                                item.tableConfig = {
                                    tableRefType: it.tableRefType
                                }
                            }
                            return item
                        })
                        if (call) call(res.data)
                        // this.templateList = res.data.templateCfgList
                    }
                },
                complete: () => {
                    this.loading = false
                }
            })
        },
        deleteTemp(e) {
            this.$confirm(this.$tt('tip_delete_template_confirm'), this.$tt('label_tip'), {
                type: 'warning'
            }).then(() => {
                this.$ajax({
                    url: this.$url['print/template/delete'],
                    method: 'post',
                    data: {
                        id: this.tempForm.id,
                    },
                    success: (res) => {
                        this.$message.success(this.$tt("tip_delete_success"))
                        this.refTypeChangeNet(this.tempForm.refType)
                        this.loadTemp(null)
                    },
                    complete: () => {
                        this.loading = false
                    }
                })
            }).catch(() => {
            });
        },

        refTypeSubmit(call) {
            this.$formRulesValidate({
                formRef: this.$refs['form'],
                rules: this.rules,
                success: () => {
                    this.loading = true
                    this.$ajax({
                        url: this.$url['print/template/update'],
                        method: 'post', type: 'json',
                        data: this.outTemplate(),
                        success: (res) => {
                            this.$message.success(this.$tt('tip_submit_success'))
                            this.return_emit(null, "reload")
                            if (!this.tempForm.id) {
                                this.tempForm.id = res.data.id
                            }
                            this.fixTabLabel(res.data.templateName)
                            // if (!this.tempForm.id) {
                            //     this.return_emit(null, "reload")
                            //     this.return_page_back()
                            //     return
                            // }
                            if (call && call instanceof Function) {
                                call()
                            } else {
                                this.return_page_back()
                            }
                        },
                        complete: () => {
                            this.loading = false
                        }
                    })
                }
            })

        },
        copyTemplate() {
            const text = JSON.stringify(this.outTemplate())
            const h = this.$createElement;
            this.$msgbox({
                title: this.$tt('label_template_data'),
                customClass: "dialog_default",
                message: h('textarea', {
                    style: {
                        'min-height': '300px',
                        'min-width': '100%',
                        'max-width': '100%',
                        width: '100%',
                    },
                    attrs: {
                        id: "template_out",
                        rows: 5
                    }
                }, [

                ]),
                showCancelButton: true,
                confirmButtonText: this.$tt('label_load_data'),
            }).then(action => {
                if (action === 'confirm') {
                    try {
                        const jsonObj = JSON.parse(document.getElementById('template_out').value)
                        delete jsonObj.id
                        this.loadTemp(jsonObj)
                    } catch (e) {

                    }
                }
            }).catch(e => { });
            this.$nextTick(() => {
                document.getElementById('template_out').value = text
            })
        },
        loadTemplateFormClipBoard() {
        },
        previewClick() {

            const defaultModel = {}
            const outModel = [
                {
                    renderItem: (h, { data }) => (<el-alert
                        class="mg_v2"
                        show-icon
                        closable={false}
                        title={this.$tt("label_preview_template_will_save")}
                        type="warning">
                    </el-alert>)
                },
            ]
            let gridTable = []
            let gridItem = null
            this.serviceParams.forEach(it => {
                if (gridItem == null) {
                    gridItem = []
                }
                const modelItem = { key: it.code, label: this.$formatNameCode(it.name, it.code), }
                const tableRefType = it.tableConfig ? it.tableConfig.tableRefType : null
                if (tableRefType && this.serviceTableParams[tableRefType]) {
                    modelItem.itemClass = ""
                    modelItem.inputClass = "w_fill"
                    defaultModel[modelItem.key] = []
                    modelItem.render = (h, { data, item }) => {
                        return h("div", {}, [
                            h("el-button", {
                                props: { type: "primary" },
                                on: {
                                    click: e => data[item.key].push({})
                                }
                            }, [this.$t("label_add_list_data")]),
                            h("ex_super_table", {
                                props: {
                                    showIndex: false,
                                    data: data[it.code],
                                    height: 200,
                                    model: this.serviceTableParams[tableRefType].tableColumnItems.map(c => {
                                        return {
                                            key: c.code, label: c.name, "min-width": 150,
                                            render: (h, { row, column }) => {
                                                return h("el-input", {
                                                    props: { value: row[column.property] },
                                                    on: { input: e => this.$set(row, column.property, e) }
                                                })
                                            }
                                        }
                                    })
                                }
                            }),
                        ])
                    }
                    gridItem.push({ span: 24, col: modelItem, },)
                } else {
                    gridItem.push({ span: 12, col: modelItem, },)
                }

                if (gridItem && _.reduce(gridItem, (sum, t) => (sum + t.span ? t.span : 24), 0) >= 24) {
                    gridTable.push(gridItem)
                    gridItem = null
                }

            })
            if (!_.isEmpty(gridItem)) {
                gridTable.push(gridItem)
            }
            outModel.push({
                grid: gridTable
            })
            this.previewDialog.form.model = outModel
            const rules = {}
            _.uniq(this.elementDrawList.filter(it => it.isRequired == true).map(it => it.code)).forEach(it => {
                rules[it] = { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }
            })
            this.previewDialog.form.rules = rules
            this.$refs.previewDialog.showNew({
                title: this.$tt("label_preview_param"),
                data: defaultModel,
                onlySetData: true,
            })
        },
        previewSubmitAfter(tempdata) {
            this.refTypeSubmit(() => {
                this.preview(Object.assign(
                    {
                        templateId: this.tempForm.id,
                        templateWidth: this.$dpi.convert(this.tempForm.canvasWidth, this.tempForm.switchUnit, 'mm') + "mm",
                        templateHeight: this.$dpi.convert(this.tempForm.canvasHeight, this.tempForm.switchUnit, 'mm') + "mm",
                        refType: this.tempForm.refType,
                    },
                    tempdata))
            })
        },

        preview(data) {
            this.previewData = null
            this.previewError = null
            const { templateId, refType, templateWidth, templateHeight, ...metadata } = data
            this.previewHeight = templateHeight
            this.previewWidth = templateWidth
            this.previewVisible = true
            this.previewLoading = true
            this.previewUrlParams = null
            this.$ajax({
                url: "/print-api/template/PrintRpc/previewPrintBase.json",
                data: {
                    type: refType,
                    templateId,
                    fileType: "png",
                    metadata: JSON.stringify(metadata),
                },
                method: 'get', responseType: "blob",
                callback: (response) => {

                    this.previewLoading = false
                    if (response.status == 200 && _.startsWith(response.headers['content-type'], 'image/')) {
                        this.previewData = window.URL.createObjectURL(response.data)
                        this.previewUrlParams = {
                            type: refType,
                            templateId,
                            metadata,
                        }
                        // this.$set(row, 'previewData', window.URL.createObjectURL(response.data))
                        // this.$set(row, 'previewDataUrl', previewLink)
                    } else {
                        var reader = new FileReader();
                        reader.onload = (event) => {
                            try {
                                var data = JSON.parse(event.target.result);
                                this.previewError = data.message || event.target.result
                            } catch (error) {
                                this.previewError = event.target.result
                            }
                        };
                        reader.readAsText(response.data);
                    }
                },
            })
        },
        printBrowser() {
            if (this.$clickFast()) return
            const previewLink = `/print-api/template/PrintRpc/previewPrintBase.json?` +
                this.$qs.stringify({
                    type: this.previewUrlParams.type,
                    templateId: this.previewUrlParams.templateId,
                    fileType: 'pdf',
                    metadata: JSON.stringify(this.previewUrlParams.metadata),
                })
            printJS({
                printable: previewLink,
                type: 'pdf',
                showModal: true
            })
        },
        printClient() {
            if (this.$clickFast()) return
            if (!this.clientId || !this.printerName) {
                return this.$message.error("请选择打印客户端")
            }
            this.$ajax({
                url: "/print-api/template/PrintRpc/print.json",
                method: 'post', type: 'json',
                loading: true,
                data: {
                    clientName: this.clientId,
                    templateId: this.previewUrlParams.templateId,
                    printerName: this.printerName,
                    type: this.previewUrlParams.type,
                    metaDataList: [
                        {
                            printNum: 1,
                            metadata: this.previewUrlParams.metadata,
                        }
                    ]
                },
                success: (res) => {
                    this.$message.success(this.$tt('label_submit_print_success'))
                },
                complete: () => {

                }
            })
        },
    },
};
</script>
<style scoped>
.contextmenuFloat {
    border: 0px solid #dcdfe6;
    background: #fff;
    cursor: pointer;
    border-radius: 8px;
    position: absolute;
    background-color: #fff;
    line-height: 24px;
    padding: 8px 0px 8px 0px;
    box-shadow: darkgrey 2px 2px 20px 1px;
    z-index: 3000;
}

.contextmenuFloat>.item {
    font-size: 14px;
    color: #666;
    padding: 5px 5px 5px 5px;
}

.contextmenuFloat>.select:hover {
    font-weight: bold;
    background-color: #edf5fe;
    color: #409eff;
}

.contextmenuFloat>.remove:hover {
    font-weight: bold;
    background-color: #edf5fe;
    color: #F56C6C;
}

.mainCancasCss {
    background: linear-gradient(90deg, rgba(206, 214, 224, .32) 1px, transparent 0), linear-gradient(rgba(206, 214, 224, .32) 1px, transparent 0);

    background-position: 0 0;
    background-repeat: repeat;
    border: 2px black solid;
}



.rectangle {
    width: 50px;
    height: 50px;
    border: 5px solid black;
}
</style>
